﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Web;

namespace MvcEngine.Core.Castle.Windsor
{
    public class WindsorConfigurator: IWindsorConfigurator
    {
        protected string configFile = "~/Windsor.config";

        public static IWindsorConfigurator Current 
        {
            get { return IoC.Resolve<IWindsorConfigurator>(); }
        }

        public WindsorConfigurator()
        {
            configFile = HttpContext.Current.Server.MapPath(configFile);
        }

        public void AddFileReference(string filePath, string moduleName)
        {
            XDocument doc = XDocument.Load(configFile);
            XElement element = new XElement("include");
            XAttribute attr = new XAttribute("uri", "file://" + filePath);
            element.Add(attr);
            attr = new XAttribute("moduleName", moduleName);
            element.Add(attr);
            doc.Root.Add(element);
            doc.Save(configFile);
        }

        public void RemoveFileReference(string moduleName)
        {
            XDocument doc = XDocument.Load(configFile);

            foreach (var item in doc.Root.Elements("include"))
            {
                var attr = item.Attributes("moduleName").FirstOrDefault();
                if (attr == null)
                    continue;
                if (attr.Value == moduleName)
                {
                    item.Remove();
                    doc.Save(configFile);
                    return;
                }
            }
        }
    }
}
